package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.sl.au.entity.Account;
import com.sl.au.entity.EXDELoginInfo;
import com.sl.au.entity.Hierarchy;
import com.sl.au.entity.Option;
import com.sl.au.entity.SaleArea;
import com.sl.au.entity.User;
import com.sl.au.repository.EXDELoginInfoRepository;
import com.sl.au.repository.UserRepository;
import com.sl.au.service.AccountService;
import com.sl.au.service.DeleteService;
import com.sl.au.service.HierarchyService;
import com.sl.au.service.IdentifyService;
import com.sl.au.service.OptionService;
import com.sl.au.service.RoleService;
import com.sl.au.service.SaleAreaService;
import com.sl.au.service.UserService;
import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings({ "restriction", "unused" })
@RestController
@RequestMapping(value = "/ui/user")
public class UserController extends BaseController {


	@Autowired
	UserService userService;
	@Autowired
	OptionService optionService;
	@Autowired
	SaleAreaService saleAreaService;
	@Autowired
	EXDELoginInfoRepository exdeLoginRepository;
	@Autowired
	HierarchyService hierarchyService;
	@Autowired
	RoleService roleService;
	@Autowired
	IdentifyService identifyService;
	@Autowired
	AccountService accountService;
	@Autowired
	DeleteService deleteService;


	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("user/userindex");
		List<Option> posts =optionService.getRepository().findByGroup("岗位");
		List<Hierarchy> hierarchys = hierarchyService.getAllNodes();
		modelAndView.addObject("posts", posts);
		modelAndView.addObject("hierarchys", hierarchys);
		modelAndView.addObject("roles", roleService.getRepository().findAll());
		return modelAndView;
	}

	/**
	 * 新增弹窗用户下拉数据
	 * @return
	 */
	@RequestMapping(value = "/getmen", method = RequestMethod.GET)
	public Map<Object,Object> getStaff(HttpServletRequest request) {
		Map<Object,Object> map = new HashMap<Object,Object>();
		List<EXDELoginInfo> men=exdeLoginRepository.getNoRole();
		map.put("men", men);
		return map;
	}
	@RequestMapping(value = "noaccount", method = RequestMethod.GET)
	public Map<String,Object> newAccount() {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("data",userService.getRepository().findAccountIsNull());
		map.put("code", 0);
		return map;
	}
	/**
	 * 保存
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Map<String, Object> saveSaleChance(HttpServletRequest request, @RequestBody Map<String, Object> models) {
		Map<String, Object> map = new HashMap<String, Object>();
		String editId = request.getParameter("editId");
		String hierarchyId = request.getParameter("hierarchy");
		Hierarchy hierarch = hierarchyService.getRepository().findOne(hierarchyId);
		User user = JSON.parseObject(JSON.toJSONString(models.get("user")), User.class);
		Account account = JSON.parseObject(JSON.toJSONString(models.get("account")), Account.class);
//		JSON.parseObject(JSON.toJSONString(map), clazz);
		int code=0;
		
		User userOne = userService.getRepository().findByContactType(user.getContactType());
		Account accountOne = this.accountService.getRepository().findByAccountName(account.getAccountName());
		if(userOne != null && !userOne.getId().equals(user.getId())) {
			code = 98;
			map.put("code", code);
			map.put("msg", "电话号已存在!");
			return map;
		}
		
		if(accountOne == null || accountOne.getId().equals(account.getId())) {
			
			Account newAccount = null;
			if(editId != null){
				User old = userService.getRepository().findOne(editId);
				/*User userEdit =userService.getRepository().findOne(editId);
				if(userEdit != null){
					userEdit.setName(user.getName());
					userEdit.setOrderNum(user.getOrderNum());
					userEdit.setPosition(user.getPosition());
					userEdit.setContactType(user.getContactType());
					userEdit.setEmail(user.getEmail());
					userEdit.setSex(user.getSex());
					userEdit.setPost(user.getPost());
					userService.getRepository().save(userEdit);	*/
				if(userService.getRepository().findOne(editId).getHierarchy() != null ) {
					if(!userService.getRepository().findOne(editId).getHierarchy().getId().equals(hierarchyId)) {
						String hierarchyOrder = identifyService.getIdentifyByType(hierarchyId,"userShow","hierarchy");
						int num = identifyService.getUserOrderByHierarchy(hierarchyId);
						if(num < 1000) {
							String orderNum = String.valueOf(num);
							user.setOrderNum(orderNum);
							String order = String.format("%03d",num);
							user.setPictureAddress(old.getPictureAddress());
							user.setHierarchy(hierarch);
							user.setOrder(hierarchyOrder+order);
							Account a=this.getMyAccount();
							code =this.userService.patch(user, a.getUser());
							User accountUser = userService.getRepository().findOne(editId);
							if(account.getId().equals("")) {
								newAccount = new Account();
								newAccount.setAccountName(account.getAccountName());
								newAccount.setIsEnabled(account.getIsEnabled());
								newAccount.setRole(account.getRole());
								newAccount.setPassword(account.getPassword());
								newAccount.setMemo(account.getMemo());
								newAccount.setUser(accountUser);
								accountService.getRepository().save(newAccount);
							}else {
								newAccount = accountService.getRepository().findOne(account.getId());
								newAccount.setAccountName(account.getAccountName());
								newAccount.setIsEnabled(account.getIsEnabled());
								newAccount.setRole(account.getRole());
								newAccount.setPassword(account.getPassword());
								newAccount.setMemo(account.getMemo());
								newAccount.setUser(accountUser);
								accountService.getRepository().save(newAccount);
							}
							code = 0;
							map.put("code", code);
							map.put("msg", "保存成功!");
						}else {
							code = 1;
							map.put("code", code);
							map.put("msg", "该组织层级人员已满,保存失败!");
						}
					}else {
						user.setPictureAddress(old.getPictureAddress());
						user.setHierarchy(old.getHierarchy());
						user.setOrder(old.getOrder());
						user.setOrderNum(old.getOrderNum());
						Account a=this.getMyAccount();
						code =this.userService.patch(user, a.getUser());
						User accountUser = userService.getRepository().findOne(editId);
						if(account.getId().equals("")) {
							newAccount = new Account();
							newAccount.setAccountName(account.getAccountName());
							newAccount.setIsEnabled(account.getIsEnabled());
							newAccount.setRole(account.getRole());
							newAccount.setPassword(account.getPassword());
							newAccount.setMemo(account.getMemo());
							newAccount.setUser(accountUser);
							accountService.getRepository().save(newAccount);
						}else {
							newAccount = accountService.getRepository().findOne(account.getId());
							newAccount.setAccountName(account.getAccountName());
							newAccount.setIsEnabled(account.getIsEnabled());
							newAccount.setRole(account.getRole());
							newAccount.setPassword(account.getPassword());
							newAccount.setMemo(account.getMemo());
							newAccount.setUser(accountUser);
							accountService.getRepository().save(newAccount);
						}
						code = 0;
						map.put("code", code);
						map.put("msg", "保存成功!");
					}
				}else {
					String hierarchyOrder = identifyService.getIdentifyByType(hierarchyId,"userShow","hierarchy");
					int num = identifyService.getUserOrderByHierarchy(hierarchyId);
					if(num < 1000) {
						String orderNum = String.valueOf(num);
						user.setOrderNum(orderNum);
						String order = String.format("%03d",num);
						user.setPictureAddress(old.getPictureAddress());
						user.setHierarchy(hierarch);
						user.setOrder(hierarchyOrder+order);
						Account a=this.getMyAccount();
						code =this.userService.patch(user, a.getUser());
						User accountUser = userService.getRepository().findOne(editId);
						if(account.getId().equals("")) {
							newAccount = new Account();
							newAccount.setAccountName(account.getAccountName());
							newAccount.setIsEnabled(account.getIsEnabled());
							newAccount.setRole(account.getRole());
							newAccount.setPassword(account.getPassword());
							newAccount.setMemo(account.getMemo());
							newAccount.setUser(accountUser);
							accountService.getRepository().save(newAccount);
						}else {
							newAccount = accountService.getRepository().findOne(account.getId());
							newAccount.setAccountName(account.getAccountName());
							newAccount.setIsEnabled(account.getIsEnabled());
							newAccount.setRole(account.getRole());
							newAccount.setPassword(account.getPassword());
							newAccount.setMemo(account.getMemo());
							newAccount.setUser(accountUser);
							accountService.getRepository().save(newAccount);
						}
						code = 0;
						map.put("code", code);
						map.put("msg", "保存成功!");
					}else {
						code = 2;
						map.put("code", 2);
						map.put("msg", "该组织层级人员已满,保存失败!");
					}
				}
			}
			else{
				String hierarchyOrder = identifyService.getIdentifyByType(hierarchyId,"userShow","hierarchy");
				int num = identifyService.getUserOrderByHierarchy(hierarchyId);
				if(num < 1000) {
					String orderNum = String.valueOf(num);
					user.setOrderNum(orderNum);
					String order = String.format("%03d",num);
					user.setHierarchy(hierarch);
					user.setOrder(hierarchyOrder+order);
					userService.saveUser(user);
					if(account.getId().equals("")) {
						newAccount = new Account();
						newAccount.setAccountName(account.getAccountName());
						newAccount.setIsEnabled(account.getIsEnabled());
						newAccount.setRole(account.getRole());
						newAccount.setPassword(account.getPassword());
						newAccount.setMemo(account.getMemo());
						newAccount.setUser(user);
						accountService.getRepository().save(newAccount);
					}else {
						newAccount = accountService.getRepository().findOne(account.getId());
						newAccount.setAccountName(account.getAccountName());
						newAccount.setIsEnabled(account.getIsEnabled());
						newAccount.setRole(account.getRole());
						newAccount.setPassword(account.getPassword());
						newAccount.setMemo(account.getMemo());
						newAccount.setUser(user);
						accountService.getRepository().save(newAccount);
					}
					code = 0;
					map.put("code", code);
					map.put("msg", "保存成功!");
				}else {
					code = 3;
					map.put("code", code);
					map.put("msg", "该组织层级人员已满,保存失败!");
				}
			}
		}else {
			code = 99;
			map.put("code", code);
			map.put("msg", "账号已存在!");
			return map;
		}
		return map;
	}
		
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<User> users =null;
		int count=0;
		if (org.springframework.util.StringUtils.hasText(key)){
			users=userService.getUsers(start, length, key, null, null);		
		}else {
			users=userService.getPage(start, length, null, null, null);			
		}
		count=userService.getCount(key);
		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value="{userId}",method = RequestMethod.DELETE)
	public Map<String, Object> deleteUser(@PathVariable String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		//int code=-1;
		//userService.delete(userId);
		map = deleteService.deleteInfo(this.datasourceName ,User.class ,userId);
		if(map.get("code").equals(0)) {
			userService.delete(userId);
			map.put("msg", "删除用户信息成功!");
		}
//		code=0;
//		map.put("code", code);
//		map.put("msg", result);
		return map;
	}

	@RequestMapping(value="getAccount/{userId}",method = RequestMethod.POST)
	public Map<String, Object> getAccount(@PathVariable String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account account = accountService.getRepository().getByUserId(userId);
		map.put("account", account);
		map.put("code", 1);
		return map;
	}
	/**
	 * 根据选择的部门过滤片区信息下拉框选项
	 */
	@RequestMapping(value = "getAreaOption", method = RequestMethod.GET)
	public Map<String, Object> getAreaOption(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String superior = request.getParameter("superior");
		List<SaleArea> saleAreas= saleAreaService.getRepository().findBySuperior(superior);
		map.put("saleAreas", saleAreas);
		return map;
	}
	//移动端获得通讯录
	@RequestMapping(value = "mobileGetPage", method = RequestMethod.GET)
	public Map<String, Object> mobileGetPage(HttpServletRequest request) {
//		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<User> users =null;
		int count=0;
		if (org.springframework.util.StringUtils.hasText(key)){
			users=userService.getUsers(start, length, key, null, null);		
		}else {
			users=userService.getPage(start, length, null, null, null);			
		}
		count=userService.getCount(key);
		Map<String, Object> map=getSortData(users);
//		map.put("data", map1);
//		map.put("draw", request.getParameter("draw"));
//		map.put("recordsFiltered", count);
//		map.put("recordsTotal", count);
		return map;
	}
    /**
     * 得到中文首字母 
     * 
     * @param str
     * @return
     */
    public static String getPinYinHeadChar(String str) {
        String convert = null;
            char[] word = str.toCharArray();
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word[0]);
            if (pinyinArray != null) {
            	char[] a=pinyinArray[0].toCharArray();
                convert =String.valueOf(a[0]);
            } else {
                convert ="1";  
            }
        return convert;
    }
    //按首字母分类
	public static Map getSortData(List<User> users) {
    	Map<String, Object> map = new HashMap<String, Object>();
//    	Map<String, Object> map1 = new HashMap<String, Object>();
    	List<User> q=new ArrayList<User>();
    	ArrayList<Integer> w=new ArrayList<Integer>();//数组w为分类情况：其中俩个一组，前一个表示首字母的Ascall码，后一个表示数量
        for(int i=97;i<=123;i++){
        	int c=0;
        	for(int j=0;j<users.size();j++){
        		if(users.get(j).getName().isEmpty()){
        			;
        		}else{
            		char[]a=getPinYinHeadChar(users.get(j).getName()).toCharArray();
            		if(a[0]==i){
            			q.add(users.get(j));
            			c++;
            		}
        		}
        		}
        	//将剩余的对象分成一类
        	if(i==123){
        		for(int x=0;x<users.size();x++){
        			Boolean j=true; 
        			for(int y=0;y<q.size();y++){
        				if(users.get(x).getId().equals(q.get(y).getId())){
        					j=false;
        				}
        			}
        			if(j){
        				q.add(users.get(x));
        				c++;
        			}
        		}
        	}
        	if(c==0){
        		;
        	}else{
        		w.add(i);
        		w.add(c);
        		map.put("record", w);
        		map.put("data", q);
        	}
        }
        return map;
    }
	//移动端保存电话号码
	@RequestMapping(value = "changeTelphoneNumber", method = RequestMethod.GET)
	public Map<String, Object> changeTelphoneNumber(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		String telphoneNumber=request.getParameter("telphoneNumber");
		User user =userService.getRepository().findOne(id);
		int judge=0;
//		if(checkMobileNumber(telphoneNumber)){
			user.setContactType(telphoneNumber);
			userService.getRepository().save(user);
			judge=1;
//		}
		map.put("data", judge);
		return map;
	}
	//移动端保存电子邮箱
	@RequestMapping(value = "changeEmail", method = RequestMethod.GET)
	public Map<String, Object> changeEmail(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		String email=request.getParameter("email");
		User user =userService.getRepository().findOne(id);
		int judge=0;
//		if(checkEmail(email)){
			user.setEmail(email);
			userService.getRepository().save(user);
			judge=1;
//		}
		map.put("data", judge);
		return map;
	}
	//移动端获得电话号码和邮箱
	@RequestMapping(value = "getEt", method = RequestMethod.GET)
	public Map<String, Object> getEt(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		User user =userService.getRepository().findOne(id);
		map.put("email", user.getEmail());
		map.put("telphoneNumber", user.getContactType());
		return map;
	}
    /**
     * 验证邮箱
     * @param email
     * @return
     */
//    public static boolean checkEmail(String email){
//        boolean flag = false;
//        try{
//                String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
//                Pattern regex = Pattern.compile(check);
//                Matcher matcher = regex.matcher(email);
//                flag = matcher.matches();
//            }catch(Exception e){
//                flag = false;
//            }
//        return flag;
//    }
     
    /**
     * 验证手机号码
     * @param mobiles
     * @return
     */
//    public static boolean checkMobileNumber(String mobileNumber){
//        boolean flag = false;
//        try{
//                Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
//                Matcher matcher = regex.matcher(mobileNumber);
//                flag = matcher.matches();
//            }catch(Exception e){
//                flag = false;
//            }
//        return flag;
//    }
}
